<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2008
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
* TEXTQP class
*
* Common functions for quotes and paraphrases
*****/
class TEXTQP
{
// Constructor
	function TEXTQP($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/MISC.php");
		include_once("core/html/HTML.php");
		include_once("core/html/FORM.php");
		$this->html = new HTML($this->db);
		include_once("core/html/TABLE.php");
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/user/USER.php");
		$this->user = new USER($db);
		include_once("core/html/CLOSE.php");
		include_once("core/keyword/KEYWORD.php");
		$this->keyword = new KEYWORD($this->db);
	}
// Display resource's quotes/paraphrases and comments
// $type is either 'quote' or 'paraphrase'
	function view($pString, $resourceId, $recordset, $type)
	{
// Load icons
		include_once("core/icons/LOADICONS.php");
		$icons = new LOADICONS();
		$icons->getIconInfo("edit");
		$viewEditLink = $icons->editExists ? "imgLink" : "link";
		$addUserId = $type == 'quote' ? 'addUserIdQuote' : 'addUserIdParaphrase';
		$textId = $type == 'quote' ? 'quoteId' : 'paraphraseId';
		$action = $type == 'quote' ? 'quoteEdit' : 'paraphraseEdit';
		$private = $type == 'quote' ? 'quotePrivate' : 'paraphrasePrivate';
		$commentTable = $type == 'quote' ? 'WKX_resource_quote_comment' : 'WKX_resource_paraphrase_comment';
		$write = $this->session->getVar('setup_write') ? TRUE : FALSE;
		$index = 0;
		$thisUserId = $this->session->getVar('setup_userId');
		if(array_key_exists("search", $this->vars) && $this->vars["search"] = 'highlight')
		{
			$searchTerms = explode(",", $this->session->getVar('search_highlight'));
			foreach($searchTerms as $term)
				$patterns[] = "/($term)(?!\S*\" \S*>)/i";
		}
		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		include_once("core/cite/CITE.php");
		$cite = new CITE($this->db, $this->vars);
		while($row = $this->db->loopRecordset($recordset))
		{
			$class = $index % 2 ? 'alternate2' : 'alternate1';
			$detail = $this->getDetails($row);
			$pString .= TABLE::trStart();
			$text = $cite->parseCitations($this->html->dbToHtmlTidy($row['text']), 'html');
			if(isset($patterns))
			{
				$url = FALSE;
/**
* Temporarily replace any URL - works for just one URL in the output string.
*/
				if(preg_match("/(<a.*>)/Ui", $text, $match))
				{
					$url = preg_quote($match[1], '/');
					$text = preg_replace("/$url/", "OSBIB__URL__OSBIB", $text);
				}
// This double replace stops stops the search term 'ass' being used to replace the 'ass' in 'class'
				$entry = preg_replace($patterns, "W!I!K!I!N!D!X!$1W!I!K!I!N!D!X!", $text);
				$text = preg_replace("/W!I!K!I!N!D!X!(.*)W!I!K!I!N!D!X!/U", MISC::span("$1", "highlight"), $entry);
//				$entry = $detail . preg_replace($patterns, MISC::span("$1", "highlight"), $text);
// Recover any URL
				if($url)
					$text = str_replace("OSBIB__URL__OSBIB", $match[1], $entry);
			}
			else
				$text = $detail . $text;
			if($row['keywords'])
			{
// Find keywords for this metadata
				$keywordIds = explode(",", $row['keywords']);
				$keywords = $conditions = array();
				foreach($keywordIds as $keywordId)
					$conditions[] = $this->db->tidyInput($keywordId);
				$condition = " WHERE " . $this->db->formatField('id') ."=" . 
					join(" OR " . $this->db->formatField('id') ."=", $conditions);
				$recordset2 = $this->db->select(array('WKX_keyword'), array('id', 'keyword'), 
					$condition . " ORDER BY " . $this->db->tidyInputClause('keyword'));
				$keywordText = MISC::br() . 
					MISC::b($this->messages->text("resources", "keywords") . ":&nbsp;&nbsp;");
				while($rowKeywords = $this->db->loopRecordSet($recordset2))
				{
					$keywords[] = $this->keyword->getKeywordLinkMeta($resourceId, $rowKeywords['id'], 
						$this->html->dbToHtmlTidy($rowKeywords['keyword']));
				}
				if(!empty($keywords))
				{
					$keywordText .= join(", ", $keywords);
					$text .= $keywordText;
				}
			}
			$text .= $this->user->displayUserAddEdit($row[$addUserId]);
// check for comments
			$recordset2 = $this->db->select(array($commentTable), array('comment', $addUserId, $private), 
				" WHERE " . $this->db->formatfield($textId) . "=" . $this->db->tidyInput($row[$textId]) . 
				" ORDER BY " . $this->db->tidyInputClause('timestamp'));
			if($this->db->numRows($recordset2))
			{
				$comment = '';
				while($rowComment = $this->db->loopRecordSet($recordset2))
				{
// Read only access
					if($this->session->getVar('setup_readOnly') && 
						(($rowComment[$private] == 'Y') || ($rowComment[$private] == 'G')))
						continue;
					else if(($rowComment[$private] == 'Y') && 
						($thisUserId != $rowComment[$addUserId]))
						continue;
// If 'G', this comment may be viewed by members of user groups of which $row[$addUserId] is a member
					else if($rowComment[$private] == 'G')
					{
						$recordset3 = $this->db->select(array('WKX_user_groups'), array('id'), 
							" WHERE FIND_IN_SET(" . $this->db->tidyInput($thisUserId) . ", 
							CONCAT(" . $this->db->formatfield('userIds') . ", ','))" . 
							" AND FIND_IN_SET(" . $this->db->tidyInput($row[$addUserId]) . ", 
							CONCAT(" . $this->db->formatfield('userIds') . ", ','))");
						if(!$this->db->numRows($recordset3))
							continue;
					}
// Else, comment is public
					$singleComment = $cite->parseCitations($this->html->dbToHtmlTidy($rowComment['comment']),
						'html');
					if(isset($patterns))
					{
						$username = $this->user->displayUserAddEdit($rowComment[$addUserId]);
						$url = FALSE;
/**
* Temporarily replace any URL - works for just one URL in the output string.
*/
						if(preg_match("/(<a.*>)/Ui", $singleComment, $match))
						{
							$url = preg_quote($match[1], '/');
							$singleComment = preg_replace("/$url/", "OSBIB__URL__OSBIB", $singleComment);
						}
// This double replace stops stops the search term 'ass' being used to replace the 'ass' in 'class'
						$singleComment = preg_replace($patterns, "W!I!K!I!N!D!X!$1W!I!K!I!N!D!X!", $singleComment);
						$singleComment = preg_replace("/W!I!K!I!N!D!X!(.*)W!I!K!I!N!D!X!/U", MISC::span("$1", "highlight"), 
							$singleComment . $username);
						$singleComment = MISC::br() . "&nbsp;" . MISC::br() . 
							MISC::b($this->messages->text("resources", "comment") . ": ") . $singleComment;
//							preg_replace($patterns, MISC::span("$1", "highlight"), $singleComment . $username);
// Recover any URL
						if($url)
							$singleComment = str_replace("OSBIB__URL__OSBIB", $match[1], $singleComment);
						$comment .= $singleComment;
					}
					else
					{
						$username = $this->user->displayUserAddEdit($rowComment[$addUserId]);
						$comment .= MISC::br() . "&nbsp;" . MISC::br() . 
							MISC::b($this->messages->text("resources", "comment") . ": ") . 
							$singleComment . $username;
					}
				}
				$pString .= TABLE::td($text . $comment, $class);
			}
			else
				$pString .= TABLE::td($text, $class);
			if($write)
			{
				$editLink = MISC::a("$viewEditLink", "&nbsp;" . $icons->edit . 
					"&nbsp;", "index.php?action=$action" . 
					htmlentities("&resourceId=" . $resourceId . "&$textId=" . $row[$textId]));
				$pString .= TABLE::td($editLink, $class, "right", "top");
			}
			$pString .= TABLE::trEnd();
			$index++;
		}
		$pString .= TABLE::tableEnd();
		$pString .= MISC::br() . "&nbsp;" . MISC::br();
		return $pString;
	}
/** 
* Get metadata details such as pages, section etc.
*/
	function getDetails($row)
	{
			$page_start = $row['page_start'] ? $row['page_start'] : FALSE;
			$page_end = $row['page_end'] ? "-" . $row['page_end'] : FALSE;
			if($page_start && $page_end)
				$page_start = 'pp.' . $page_start;
			else if($page_start)
				$page_start = 'p.' . $page_start;
			$page = $page_start? $page_start . $page_end : FALSE;
			if($page)
				$details[] = $page;
			$paragraph = $row['paragraph'] ? $row['paragraph'] : FALSE;
			if($paragraph)
				$details[] = $this->messages->text("resources", "paragraph") . "&nbsp;" . $paragraph;
			$section = $row['section'] ? $row['section'] : FALSE;
			if($section)
				$details[] = $this->messages->text("resources", "section") . "&nbsp;" . $section;
			$chapter = $row['chapter'] ? $row['chapter'] : FALSE;
			if($chapter)
				$details[] = $this->messages->text("resources", "chapter") . "&nbsp;" . $chapter;
			return isset($details) ? MISC::b(MISC::i(join(", ", $details))) . "&nbsp;&nbsp;" : FALSE;
	}
// display the editing form:
// Only the original poster can edit the quote/paraphrase and only the original posters can edit their comment
// $type is either 'quote' or 'paraphrase'
	function editDisplay($type)
	{
		include_once("core/cite/CITE.php");
		$cf = new CITE($this->db, $this->vars);
		$textId = $type == 'quote' ? 'quoteId' : 'paraphraseId';
		$action = $type == 'quote' ? 'quoteEdit' : 'paraphraseEdit';
		$addUserId = $type == 'quote' ? 'addUserIdQuote' : 'addUserIdParaphrase';
		$pageStart = $type == 'quote' ? 'quotePageStart' : 'paraphrasePageStart';
		$pageEnd = $type == 'quote' ? 'quotePageEnd' : 'paraphrasePageEnd';
		$paragraph = $type == 'quote' ? 'quoteParagraph' : 'paraphraseParagraph';
		$section = $type == 'quote' ? 'quoteSection' : 'paraphraseSection';
		$chapter = $type == 'quote' ? 'quoteChapter' : 'paraphraseChapter';
		$typeText = $type == 'quote' ? 'quoteText' : 'paraphraseText';
		$keywords = $type == 'quote' ? 'quote_keywords' : 'paraphrase_keywords';
		$typeComment = $type == 'quote' ? 'quoteComment' : 'paraphraseComment';
		$privateComment = $type == 'quote' ? 'quotePrivate' : 'paraphrasePrivate';
		$commentTable = $type == 'quote' ? 'WKX_resource_quote_comment' : 'WKX_resource_paraphrase_comment';
		$userId = $this->session->getVar('setup_userId');
		$hidden = FORM::hidden("resourceId", $this->vars['resourceId']);
		$page_start = $page_end = $db_paragraph = $db_section = $db_chapter = 
			$text = $comment = $td = $rowKeywords = FALSE;
		$private = 'N';
// are we editing or adding?
		if(array_key_exists($textId, $this->vars))
		{
			$hidden .= FORM::hidden($textId, $this->vars[$textId]);
			$sql = $type == 'quote' ? 
				$this->db->selectNoExecute(array('WKX_resource_quote', 'WKX_resource_quote_text'), 
				array(array('WKX_resource_quote.id' => 'quoteId'), 'page_start', 'page_end', 
				'paragraph', 'section', 'chapter', 'text', $addUserId, $keywords), 
				" WHERE WKX_resource_quote.id=" . $this->db->tidyInput($this->vars[$textId]) . 
				" AND WKX_resource_quote.id=WKX_resource_quote_text.id") 
				:
				$this->db->selectNoExecute(array('WKX_resource_paraphrase', 'WKX_resource_paraphrase_text'), 
				array(array('WKX_resource_paraphrase.id' => 'paraphraseId'), 'page_start', 'page_end', 
				'paragraph', 'section', 'chapter', 'text', $addUserId, $keywords), 
				" WHERE WKX_resource_paraphrase.id=" . $this->db->tidyInput($this->vars[$textId]) . 
				" AND WKX_resource_paraphrase.id=WKX_resource_paraphrase_text.id");
			$row = $this->db->fetchRow($this->db->query($sql));
			$rowKeywords = $row[$keywords];
			$page_start = $this->html->dbToFormTidy($row['page_start']);
			$db_paragraph = $this->html->dbToFormTidy($row['paragraph']);
			$db_section = $this->html->dbToFormTidy($row['section']);
			$db_chapter = $this->html->dbToFormTidy($row['chapter']);
			if($row['page_end'])
				$page_end = $this->html->dbToFormTidy($row['page_end']);
			if($userId == $row[$addUserId])
				$text = $this->html->dbToFormTidy($row['text']);
			else
				$text = $this->html->dbToHtmlTidy($row['text']);
			$recordset = $this->db->select(array($commentTable), array('id', 'comment', 
				$addUserId, $privateComment), 
				" WHERE " . $this->db->formatfield($addUserId) . "=" . $this->db->tidyInput($userId) . 
				" AND " . $this->db->formatfield($textId) . "=" . 
				$this->db->tidyInput($this->vars[$textId]));
			if($this->db->numRows($recordset))
			{
				$rowComment = $this->db->fetchRow($recordset);
				$comment = $this->html->dbToFormTidy($rowComment['comment']);
				$private = $rowComment[$privateComment];
			}
		}
		if(isset($row) && $userId != $row[$addUserId])
			$hidden .= FORM::hidden("commentOnly", TRUE);

		$pString = TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$pString .= TABLE::trStart();
		if(!isset($row) || ($text && ($userId == $row[$addUserId])))
			$pString .= $this->displayKeywordForm($type, $rowKeywords);
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();

// Encapsulating cell from body.tpl
		$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();

		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$pString .= TABLE::trStart();
		if(!$text || ($text && ($userId == $row[$addUserId])))
		{
			$td = $hidden . FORM::textInput($this->messages->text("resources", "page"), 
				$pageStart, $page_start, 6, 5);
			$td .= " - " . FORM::textInput(FALSE, $pageEnd, $page_end, 6, 5);
			$pString .= TABLE::td($td);
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "paragraph"), 
				$paragraph, $db_paragraph, 11, 10));
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "section"), 
				$section, $db_section, 20));
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "chapter"), 
				$chapter, $db_chapter, 20));
		}
		else if($page_start && $page_end)
			$page = MISC::b('pp.' . $page_start . $page_end) . "&nbsp;";
		else if($page_start)
			$page = MISC::b('p.' . $page_start . $page_end) . "&nbsp;";
		else
			$page = FALSE;
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();

// Encapsulating cell from body.tpl
		$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
		$pString .= MISC::br() . "&nbsp;" . MISC::br();
		$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();

		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$pString .= TABLE::trStart();
		$hint = ($type == 'quote') ? MISC::br() . $this->messages->text("hint", $type) : FALSE;
// Create citation link for this type
		$citeLink = $cf->makeCiteLink($type);
// The second parameter ($typeText) to textareaInput is the textarea name
		if(!$text || ($text && ($userId == $row[$addUserId])))
			$pString .= TABLE::td(FORM::textareaInput($this->messages->text("resources", $type), 
			$typeText, $text, 80, 10) . $citeLink . $hint);
		else
			$pString .= $hidden . TABLE::td($page . $cf->parseCitations($text, 'html'), 'alternate1') . 
			TABLE::td("&nbsp;");
		$pString .= TABLE::trEnd();
		$pString .= TABLE::trStart();
		$pString .= TABLE::td(MISC::br() . "&nbsp;" . MISC::br());
		$pString .= TABLE::trEnd();
		$pString .= TABLE::trStart();
// Create citation link for this type
		$citeLink = $cf->makeCiteLink($type . "Comment");
// The second parameter ($typeComment) to textareaInput is the textarea name
		$pString .= TABLE::td(FORM::textareaInput($this->messages->text("resources", "comment"), 
			$typeComment, $comment, 80, 10) . $citeLink . MISC::br() . 
			$this->messages->text("hint", "format"));
		$pString .= TABLE::trEnd();
		$recordset3 = $this->db->select(array('WKX_user_groups'), array('id'), 
					" WHERE FIND_IN_SET(" . $this->db->tidyInput($userId) . ", 
					CONCAT(" . $this->db->formatfield('userIds') . ", ','))");
		if($this->db->numRows($recordset3))
		{
			$privateArray = array('N' => $this->messages->text("resources", "public"), 
				'Y' => $this->messages->text("resources", "private"), 
				'G' => $this->messages->text("resources", "availableToGroups"));
			$privateForm = FORM::selectedBoxValue($this->messages->text("resources", "commentPrivate"), 
				"private", $privateArray, $private, 3);
		}
		else
		{
			$privateArray = array('N' => $this->messages->text("resources", "public"), 
				'Y' => $this->messages->text("resources", "private"));
			$privateForm = FORM::selectedBoxValue($this->messages->text("resources", "commentPrivate"), 
				"private", $privateArray, $private, 2);
		}
		$pString .= TABLE::trStart();
		$pString .= TABLE::td(MISC::p($privateForm . "&nbsp;&nbsp;" . FORM::formSubmit("Proceed")));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();

// display other comments
		if($text)
		{
// Encapsulating cell from body.tpl
			$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
			$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
			$recordset = $this->db->select(array($commentTable), array('comment', $addUserId, $privateComment), 
				" WHERE " . $this->db->formatfield($textId) . "=" . $this->db->tidyInput($row[$textId]) . 
				" AND " . $this->db->formatfield($addUserId) . "!=" . $this->db->tidyInput($userId) . 
				" ORDER BY " . $this->db->tidyInputClause('timestamp') . " DESC");
			if($this->db->numRows($recordset))
			{
				$pString .= TABLE::trStart();
				$pString .= TABLE::td(MISC::hr());
				$pString .= TABLE::trEnd();
			}
			$index = 0;
			while($row = $this->db->loopRecordSet($recordset))
			{
				if(($row[$privateComment] == 'Y') && 
					($userId != $row[$addUserId]))
					continue;
// If 'G', this comment may be viewed by members of user groups of which $row[$addUserId] is a member
				else if($row[$privateComment] == 'G')
				{
					$recordset3 = $this->db->select(array('WKX_user_groups'), array('id'), 
						" WHERE FIND_IN_SET(" . $this->db->tidyInput($userId) . ", 
						CONCAT(" . $this->db->formatfield('userIds') . ", ','))" . 
						" AND FIND_IN_SET(" . $this->db->tidyInput($row[$addUserId]) . ", 
						CONCAT(" . $this->db->formatfield('userIds') . ", ','))");
					if(!$this->db->numRows($recordset3))
						continue;
				}
// Else, comment is public
				$class = $index++ % 2 ? 'alternate2' : 'alternate1';
				$username = $this->user->displayUserAddEdit($row[$addUserId]);
				$pString .= TABLE::trStart();
				$pString .= TABLE::td($cf->parseCitations($this->html->dbToHtmlTidy($row['comment']), 'html') . 
					$username, $class);
				$pString .= TABLE::trEnd();
			}
			$pString .= TABLE::tableEnd();
// Encapsulating cell from body.tpl
		}
		return $pString;
	}
// Display keywords form
	function displayKeywordForm($type, $rowKeywords)
	{
		$keywords = $this->keyword->grabAll();
// add 0 => IGNORE to keywords array
		$temp = array();
		if($keywords)
		{
			$temp[0] = $this->messages->text("misc", "ignore");
			foreach($keywords as $key => $value)
				$temp[$key] = $value;
			$keywords = $temp;
		}
		if($type == 'quote')
			$hint = $this->messages->text("hint", "keywords", " " . 
				strtolower($this->messages->text("resources", "quote")));
		else if($type == 'paraphrase')
			$hint = $this->messages->text("hint", "keywords", " " . 
				strtolower($this->messages->text("resources", "paraphrase")));
		else
			$hint = $this->messages->text("hint", "keywords", " " . 
				strtolower($this->messages->text("resources", "musing")));
		$pString = TABLE::td(MISC::b($this->messages->text("resources", "keywords")) . MISC::br() . 
			$hint . MISC::p(FORM::textInput(FALSE, 
			"keywords", FALSE, 40, 255) . MISC::br() . 
			$this->messages->text("hint", "keywordList")));
		if($keywords)
		{
			if($rowKeywords)
			{
				$selectedArray = explode(",", $rowKeywords);
				$td = FORM::selectedBoxValueMultiple(FALSE, "keyword_ids", 
				$keywords, $selectedArray, "6");
			}
			else
				$td = FORM::selectFBoxValueMultiple(FALSE, "keyword_ids", $keywords, "6");
			$pString .= TABLE::td($td . MISC::br() . $this->messages->text("hint", "multiples"));
		}
		return $pString;
	}
// write to the database.
// if there is no 'quoteId'/'paraphraseId' input, we are adding a new quote/paraphrase.  Otherwise, editing one.
// $type is either 'quote' or 'paraphrase'
	function edit($type)
	{
		$textId = $type == 'quote' ? 'quoteId' : 'paraphraseId';
		$addUserId = $type == 'quote' ? 'addUserIdQuote' : 'addUserIdParaphrase';
		$pageStart = $type == 'quote' ? 'quotePageStart' : 'paraphrasePageStart';
		$pageEnd = $type == 'quote' ? 'quotePageEnd' : 'paraphrasePageEnd';
		$paragraph = $type == 'quote' ? 'quoteParagraph' : 'paraphraseParagraph';
		$section = $type == 'quote' ? 'quoteSection' : 'paraphraseSection';
		$chapter = $type == 'quote' ? 'quoteChapter' : 'paraphraseChapter';
		$typeText = $type == 'quote' ? 'quoteText' : 'paraphraseText';
		$typeComment = $type == 'quote' ? 'quoteComment' : 'paraphraseComment';
		$privateComment = $type == 'quote' ? 'quotePrivate' : 'paraphrasePrivate';
		$typeTable = $type == 'quote' ? 'WKX_resource_quote' : 'WKX_resource_paraphrase';
		$textTable = $type == 'quote' ? 'WKX_resource_quote_text' : 'WKX_resource_paraphrase_text';
		$tableKeywords = $type == 'quote' ? 'quote_keywords' : 'paraphrase_keywords';
		$commentTable = $type == 'quote' ? 'WKX_resource_quote_comment' : 'WKX_resource_paraphrase_comment';
		$commentTableId = $type == 'quote' ? 'quoteId' : 'paraphraseId';
		$summaryType = $type == 'quote' ? 'quotes' : 'paraphrases';
		$userId = $this->session->getVar('setup_userId');
		if(!array_key_exists('keyword_ids', $this->vars))
			$this->vars['keyword_ids'] = array();
		if(array_key_exists($typeText, $this->vars) && $this->vars[$typeText])
			$keywordIds = $this->keyword->writeKeywordTable(array('keywords' => 
				$this->vars['keywords'], 'keyword_ids' => join(",", $this->vars['keyword_ids'])));
// insert?
		if(!array_key_exists($textId, $this->vars))
		{
			if(!array_key_exists($typeText, $this->vars) || !$this->vars[$typeText])
				return FALSE;
			if(isset($keywordIds) && $keywordIds)
			{
				foreach($keywordIds as $value)
				{
					if($value)
						$temp[] = $value;
				}
				if(isset($temp))
				{
					$fields[] = $type . "_keywords";
					$values[] = implode(',', $temp);
// remove cache files for keywords
					$this->db->deleteCache('resourceKeywords');
					$this->db->deleteCache('metadataKeywords');
					$this->db->deleteCache('quoteKeywords');
					$this->db->deleteCache('paraphraseKeywords');
					$this->db->deleteCache('musingKeywords');
				}
			}
			$addEdit = 'added';
			$fields[] = 'resourceId';
			$values[] = $this->vars['resourceId'];
			if(array_key_exists($pageStart, $this->vars) && $this->vars[$pageStart])
			{
				$fields[] = 'page_start';
				$values[] = trim(strtolower($this->vars[$pageStart]));
				if(array_key_exists($pageEnd, $this->vars) && $this->vars[$pageEnd])
				{
					$fields[] = 'page_end';
					$values[] = trim(strtolower($this->vars[$pageEnd]));
				}
			}
			if(array_key_exists($paragraph, $this->vars) && $this->vars[$paragraph])
			{
				$fields[] = 'paragraph';
				$values[] = trim(strtolower($this->vars[$paragraph]));
			}
			if(array_key_exists($section, $this->vars) && $this->vars[$section])
			{
				$fields[] = 'section';
				$values[] = trim(strtolower($this->vars[$section]));
			}
			if(array_key_exists($chapter, $this->vars) && $this->vars[$chapter])
			{
				$fields[] = 'chapter';
				$values[] = trim(strtolower($this->vars[$chapter]));
			}
			$this->db->insert($typeTable, $fields, $values);
			$lastAutoId = $this->db->lastAutoId($typeTable);
			$this->db->deleteCache('metadataCreators');
			$this->db->deleteCache('metadataCollections');
			$this->db->deleteCache('metadataPublishers');
			$fields = $values = array();
			$fields[] = 'id';
			$values[] = $lastAutoId;
			$fields[] = 'text';
			$values[] = trim($this->vars[$typeText]);
			if($userId)
			{
				$fields[] = $addUserId;
				$values[] = $userId;
			}
			$this->db->insert($textTable, $fields, $values);
			$this->summary(1, $summaryType);
// Write comments table
			if(array_key_exists($typeComment, $this->vars) && $this->vars[$typeComment])
			{
				$fields = $values = array();
				$fields[] = $commentTableId;
				$values[] = $lastAutoId;
				if($userId)
				{
					$fields[] = $addUserId;
					$values[] = $userId;
				}
				$fields[] = 'comment';
				$values[] = trim($this->vars[$typeComment]);
				if(array_key_exists('private', $this->vars) && ($this->vars['private'] == 'Y'))
				{
					$fields[] = $privateComment;
					$values[] = 'Y';
				}
				else if(array_key_exists('private', $this->vars) && ($this->vars['private'] == 'G'))
				{
					$fields[] = $privateComment;
					$values[] = 'G';
				}
				else
				{
					$fields[] = $privateComment;
					$values[] = 'N';
				}
				$fields[] = 'timestamp';
				$values[] = $this->db->formatTimestamp();
				$this->db->insert($commentTable, $fields, $values);
			}
		}
// else edit/delete?
		else
		{
			$addEdit = 'edited';
// Grab the keywords left in this metadata
			$checkKeywords = FALSE;
			if(isset($keywordIds) && $keywordIds)
			{
				$recordset = $this->db->select(array($typeTable), array($tableKeywords), 
					" WHERE " . $this->db->formatfield('id') . "=" . 
					$this->db->tidyInput($this->vars[$textId]));
				$row = $this->db->fetchRow($recordset);
				if(!empty($row))
					$checkKeywords = array_diff(explode(",", $row[$tableKeywords]), $keywordIds);
			}
// if quoteText is empty, delete the row if this is the quote owner
			if(!array_key_exists('commentOnly', $this->vars) && !$this->vars[$typeText])
			{
				$recordset = $this->db->select(array($typeTable), array($tableKeywords), 
					" WHERE " . $this->db->formatfield('id') . "=" . 
					$this->db->tidyInput($this->vars[$textId]));
				$row = $this->db->fetchRow($recordset);
				if(!empty($row))
					$checkKeywords = explode(",", $row[$tableKeywords]);
				$addEdit = 'deleted';
				$this->db->delete($typeTable, "WHERE " . $this->db->formatField('id') . "=" . 
					$this->db->tidyInput($this->vars[$textId]));
				$this->db->delete($textTable, "WHERE " . $this->db->formatField('id') . "=" . 
					$this->db->tidyInput($this->vars[$textId]));
				$this->db->delete($commentTable, "WHERE " . $this->db->formatField($textId) . "=" . 
					$this->db->tidyInput($this->vars[$textId]));
				$this->db->optimize($typeTable);
				$this->db->optimize($textTable);
				$this->db->optimize($commentTable);
				$metadataExists = $this->summary(-1, $summaryType);
// remove cache files for keywords
				$this->db->deleteCache('resourceKeywords');
				$this->db->deleteCache('metadataKeywords');
				$this->db->deleteCache('quoteKeywords');
				$this->db->deleteCache('paraphraseKeywords');
				$this->db->deleteCache('musingKeywords');
// Remove these cache files if no metadata left in resource
				if(!$metadataExists)
				{
					$this->db->deleteCache('metadataCreators');
					$this->db->deleteCache('metadataCollections');
					$this->db->deleteCache('metadataPublishers');
				}
			}
			else
			{
				$addEdit = 'edited';
// Quote/paraphrase _text table
				if(!array_key_exists('commentOnly', $this->vars))
				{
					$updateArray['text'] = trim($this->vars[$typeText]);
					$this->db->update($textTable, $updateArray, 
						"WHERE " . $this->db->formatField('id') . "=" . 
						$this->db->tidyInput($this->vars[$textId]));
				}
// Comment
				$updateArray = array();
				if(array_key_exists($typeComment, $this->vars) && trim($this->vars[$typeComment]))
				{
// Is this a new comment or are we editing an old comment?
					$recordset = $this->db->select(array($commentTable), 
						array('id', 'comment', $addUserId), 
						" WHERE " . $this->db->formatfield($addUserId) . "=" . 
						$this->db->tidyInput($userId) . 
						" AND " . $this->db->formatfield($textId) . "=" . 
						$this->db->tidyInput($this->vars[$textId]));
// edit existing comment
					if($this->db->numRows($recordset))
					{
						$updateArray['comment'] = trim($this->vars[$typeComment]);
						if(array_key_exists('private', $this->vars) && ($this->vars['private'] == 'Y'))
							$updateArray[$privateComment] = 'Y';
						else if(array_key_exists('private', $this->vars) && ($this->vars['private'] == 'G'))
							$updateArray[$privateComment] = 'G';
						else
							$updateArray[$privateComment] = 'N';
						$this->db->update($commentTable, $updateArray, 
							" WHERE " . $this->db->formatfield($addUserId) . "=" . 
							$this->db->tidyInput($userId) . 
							" AND " . $this->db->formatfield($textId) . "=" . 
							$this->db->tidyInput($this->vars[$textId]));
// Update timestamp
						$this->db->update($commentTable, 
							array('timestamp' => $this->db->formatTimestamp()), 
							" WHERE " . $this->db->formatField($textId) . "=" . 
							$this->db->tidyInput($this->vars[$textId]));
					}
// new comment
					else
					{
						if(array_key_exists('private', $this->vars) && ($this->vars['private'] == 'Y'))
							$private = 'Y';
						else if(array_key_exists('private', $this->vars) && ($this->vars['private'] == 'G'))
							$private = 'G';
						else
							$private = 'N';
						$fields[] = $textId;
						$values[] = trim($this->vars[$textId]);
						$fields[] = $addUserId;
						$values[] = $userId;
						$fields[] = 'comment';
						$values[] = trim($this->vars[$typeComment]);
						$fields[] = $privateComment;
						$values[] = $private;
						$fields[] = 'timestamp';
						$values[] = $this->db->formatTimestamp();
						$this->db->insert($commentTable, $fields, $values);
					}
				}
// remove comment row
				else
				{
					$this->db->delete($commentTable, 
						"WHERE " . $this->db->formatField($textId) . "=" . 
						$this->db->tidyInput($this->vars[$textId]) . 
						" AND " . $this->db->formatfield($addUserId) . "=" . 
						$this->db->tidyInput($userId));
					$this->db->optimize($commentTable);
				}
// Quote/paraphrase main type table
				$updateArray = $nulls = array();
// page number lowercased in case roman numerals input!
				if(array_key_exists($pageStart, $this->vars) && $this->vars[$pageStart])
				{
					$updateArray['page_start'] = 
						trim(strtolower($this->vars[$pageStart]));
					if(array_key_exists($pageEnd, $this->vars) && $this->vars[$pageEnd])
					{
						$updateArray['page_end'] = 
							trim(strtolower($this->vars[$pageEnd]));
					}
					else
						$nulls[] = 'page_end';
				}
				else
				{
					$nulls[] = 'page_start';
					$nulls[] = 'page_end';
				}
				if(array_key_exists($paragraph, $this->vars) && $this->vars[$paragraph])
				{
					$updateArray['paragraph'] = 
						trim($this->vars[$paragraph]);
				}
				else
					$nulls[] = 'paragraph';
				if(array_key_exists($section, $this->vars) && $this->vars[$section])
				{
					$updateArray['section'] = 
						trim($this->vars[$section]);
				}
				else
					$nulls[] = 'section';
				if(array_key_exists($chapter, $this->vars) && $this->vars[$chapter])
				{
					$updateArray['chapter'] = 
						trim($this->vars[$chapter]);
				}
				else
					$nulls[] = 'chapter';
				if(isset($keywordIds) && $keywordIds)
				{
					foreach($keywordIds as $value)
					{
						if($value)
							$temp[] = $value;
					}
					if(isset($temp))
						$updateArray[$type . '_keywords'] = join(",", $temp);
				}
				else
					$nulls[] = $type . '_keywords';
				if(!empty($updateArray))
					$this->db->update($typeTable, $updateArray, 
						"WHERE " . $this->db->formatField('id') . "=" . 
						$this->db->tidyInput($this->vars[$textId]));
				if(!empty($nulls))
					$this->db->updateNull($typeTable, $nulls, 
						"WHERE " . $this->db->formatField('id') . "=" . 
						$this->db->tidyInput($this->vars[$textId]));
			}
			if($checkKeywords)
				$this->keyword->removeHanging2(join(",", $checkKeywords));
		}
// email notification
		include_once("core/notify/NOTIFY.php");
		$notify = new NOTIFY($this->db);
		$notify->email($this->vars['resourceId']);
		return $addEdit;
	}
// update or insert WKX_resource_summary
	function summary($incDec, $field)
	{
		$metadataExists = TRUE;
		$totalsField = $field == 'quotes' ? 'totalQuotes' : 'totalParaphrases';
// if row exists, update, else insert.
		$recordset = $this->db->select(array('WKX_resource_summary'), array('id'), 
			" WHERE " . $this->db->formatField('id') . "=" . 
			$this->db->tidyInput($this->vars['resourceId']));
		if($this->db->numRows($recordset))
			$this->db->updateSingle('WKX_resource_summary', $this->db->formatField($field) . "=" .  
			"COALESCE(" . $this->db->formatField($field) . "+" . 
			$this->db->tidyInput($incDec) . ", " . $this->db->tidyInput($incDec) . ")");
		else
			$this->db->insert('WKX_resource_summary', array('id', $field), 
			array($this->vars['resourceId'], 1));
// if a decrement leaves nothing, delete row.
		$recordset = $this->db->select(array('WKX_resource_summary'), 
			array('musings', 'paraphrases', 'quotes'), 
			" WHERE " . $this->db->formatField('id') . "=" . 
			$this->db->tidyInput($this->vars['resourceId']));
		$row = $this->db->fetchRow($recordset);
		if(!$row['musings'] && !$row['paraphrases'] && !$row['quotes'])
		{
			$this->db->delete('WKX_resource_summary', 
				"WHERE " . $this->db->formatField('id') . "=" . 
				$this->db->tidyInput($this->vars['resourceId']));
			$this->db->optimize('WKX_resource_summary');
			$metadataExists = FALSE;
		}
// update master summary table
		$this->db->updateSingle('WKX_database_summary', $this->db->formatField($totalsField) .  
			"=" . $this->db->formatField($totalsField) . "+" . $this->db->tidyInput($incDec));
		return $metadataExists;
	}
}
?>
